<?php
/**
 * Created by PhpStorm.
 * User: wangg
 * Date: 2017/7/10 0010
 * Time: 9:59
 */

namespace app\admin\controller;


use app\common\model\Qbank;
use app\common\model\QbankName;
use app\common\model\QbankType;
use think\Loader;
use think\Request;
use think\Response;
use think\Session;
use think\Validate;

/**
 * Class Question
 * @package app\admin\controller
 */
class Question extends Common
{
    /**
     * @return \think\response\View
     */
    public function lst()
    {
        $artres = Qbank::with('bankname', 'type', 'user')->order('qid', 'esc')->paginate(20, false,
            ['type' => 'myPaginate'
            ]);
        $num = count(Qbank::all());
        $this->assign('method', __METHOD__);
        $this->assign('artres', $artres);
        $this->assign('num', $num);
        return view('/question/lst');
    }

    /**
     * @return \think\response\View|void
     */
    public function add()
    {

        if (request()->isPost()) {
            //return dump(Request::instance()->param());
            $data = Request::instance()->post();
            $data['time'] = time();
            $data['uid'] = Request::instance()->session('id');
            $validate = Loader::validate('Question');
            if (!$validate->scene('add')->check($data)) {
                $this->error($validate->getError());
            }
            $Question['content'] = $data['content'];
            $Question['uid'] = $data['uid'];
            $Question['qbank'] = $data['qbank_id'];
            $Question['qtype'] = $data['qtype_id'];
            $Question['qa'] = $data['qa'];
            $Question['created_time'] = date('Y-m-d H:i:s', $data['time']);
            $Question['qnum']=$data['qnum'];

            $abc = "ABCDEFG";
            if ($data['qtype_id'] == 4 or $data['qtype_id'] == 5) {
                $Question['qans'] = '';
            } else {
                if ($data['qtype_id'] == 3) {
                    $data['qnum'] = 2;
                }
                for ($i = 0; $i < $data['qnum']; $i++) {
                    $Que_Ans[$abc[$i]] = $data['q_type' . $Question['qtype'] . '_' . $abc[$i]];
                }
                $Question['qans'] = htmlspecialchars(json_encode($Que_Ans));
            }
            $quest = new Qbank();
            if ($quest->save($Question)) {
                $this->success('添加题目成功');
            } else {
                $this->error('添加题目失败');
            }
            return;
        }

        if ($this->request->isGet()) {
            //获取所有题库名称
            $cate = new QbankName();
            $bankList = $cate->bankList();
            $this->assign('bankList', $bankList);

            //获取题型种类
            $q_type = new QbankType();
            $typeList = $q_type->typeList();
            $this->assign('typeList', $typeList);

            return view();
        }
    }

    /**
     * @param int $id
     * @return \think\response\View|void
     */
    public function edit(int $id)
    {
        if (request()->isPost()) {
            $data = Request::instance()->post();
            $data['time'] = time();
            $data['uid'] = Request::instance()->session('id');

            $validate = \think\Loader::validate('Question');
            if (!$validate->scene('edit')->check($data)) {
                $this->error($validate->getError());
            }
            $Question['qid'] = $id;
            $Question['content'] = $data['content'];
            $Question['uid'] = $data['uid'];
            $Question['qbank'] = $data['qbank_id'];
            $Question['qtype'] = $data['qtype_id'];
            $Question['qa'] = $data['qa'];
            $Question['created_time'] = date('Y-m-d H:i:s', $data['time']);
            $Question['qnum']=$data['qnum'];

            $abc = "ABCDEFG";
            if ($data['qtype_id'] == 4 or $data['qtype_id'] == 5) {
                $Question['qans'] = '';
            } else {
                if ($data['qtype_id'] == 3) {
                    $data['qnum'] = 2;
                }
                if ($data['qtype_id'] == 1 or $data['qtype_id'] == 2) {
                    if ($data['qnum'] == '') {
                        $data['qnum'] = count((array)json_decode(Qbank::get($id)->qans));
                    }
                }
                for ($i = 0; $i < $data['qnum']; $i++) {
                    $Que_Ans[$abc[$i]] = $data['q_type' . $Question['qtype'] . '_' . $abc[$i]];
                }
                $Question['qans'] = htmlspecialchars(json_encode($Que_Ans));
            }


            $article = new Qbank();
            $save = $article->update($Question);
            if ($save) {
                $this->success('修改文章成功！');
            } else {
                $this->error('修改文章失败！');
            }
            return;
        }
        if ($this->request->isGet()) {

            if (!is_numeric($id)) {
                return;
            }

            $cate = new QbankName();
            $bankList = $cate->bankList();
            $this->assign('bankList', $bankList);

            //获取题型种类
            $q_type = new QbankType();
            $typeList = $q_type->typeList();
            $this->assign('typeList', $typeList);

            $qbank = Qbank::get($id);
            $this->assign('question', $qbank);
            return view();
        }
    }

    /**
     *
     */
    public function del()
    {
        if (Qbank::destroy(input('id'))) {
            $this->success('删除文章成功！');
        } else {
            $this->error('删除文章失败！');
        }
    }

    /**
     * 题库搜索，日期筛选功能
     * @return \think\response\View
     */
    public function search()
    {
        $data = Request::instance()->post();
        if ($data['start'] == '') {
            $data['start'] = '1970-01-01 00:00:00';
        }
        if ($data['end'] == '') {
            $data['end'] = date('Y-m-d H:i:s', time('+8'));
        }
        $start = $data['start'];
        $end = $data['end'];
        $keyword = $data['keyword'];
        $sub = strtotime($data['end']) - strtotime($data['start']);
        if ($sub < 0) {
            $this->error('日期非法');
        } else {
            if ($keyword == '') {
                $question = Qbank::where('created_time', '>=', $start)->where('created_time', '<=', $end)->order('qid', 'asc')->select();
            } else {
                $question = Qbank::where('content', 'like', '%' . $keyword . '%')->where('created_time', '>=', $start)->where('created_time', '<=', $end)->order('qid', 'asc')->select();
            }
            $num = count($question);
            $this->assign('method', __METHOD__);
            $this->assign('artres', $question);
            $this->assign('num', $num);
            return view('/question/lst');
        }
    }

    public function addQuestionBank()
    {
        $exc = Request::instance()->file('excel');
        if (!$exc) {
            $this->error('文件错误');
        }
        if (mime_content_type($exc->getPathname()) == 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') {

            $excel = \PHPExcel_IOFactory::createReader('Excel2007');
            $phpexc = $excel->load($exc->getPathname());
            $a = $phpexc->getSheet(0);
            $questions_num = $a->getHighestRowAndColumn()['row'] - 1;
            $abc = "ABCDEFGHIJK";
            for ($i = 0; $i < $questions_num; $i++) {
                $questions[$i]['uid'] = Session::get('admin')['id'];
                $questions[$i]['content'] = $a->getCell('C' . ($i + 2))->getValue();
                $questions[$i]['qtype'] = $a->getCell('B' . ($i + 2))->getValue();
                $questions[$i]['qbank'] = $a->getCell('A' . ($i + 2))->getValue();
                $questions[$i]['qa'] = $a->getCell('E' . ($i + 2))->getValue();
                if ($questions[$i]['qtype'] == 4 || $questions[$i]['qtype'] == 5) {
                    $questions[$i]['qans'] = '';
                } else {
                    for ($b = 0; $b < $a->getCell('D' . ($i + 2))->getValue(); $b++) {
                        $qans[$abc[$b]] = $a->getCell($abc[$b + 5] . ($i + 2))->getValue();
                    }
                    $questions[$i]['qans'] = json_encode($qans);
                }
                $questions[$i]['created_time'] = date('Y-m-d H:i:s', time());
            }
            foreach ($questions as $question) {
                $que = new Qbank();
                $que->save($question);
            }
            $this->success('导入成功，请认真检查题库内容是否正确');
        } else {
            $this->error('错误的文件类型，只接受xlsx格式');
        }


    }
}